package com.shengqi.xinnongren.work.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.shengqi.xinnongren.R;
import com.shengqi.xinnongren.common.utils.ToastHelper;
import com.shengqi.xinnongren.work.dialog.presenter.AddToCarPresenter;
import com.shengqi.xinnongren.work.dialog.view.AddToCarView;
import com.shengqi.xinnongren.work.ui.Global;
import com.shengqi.xinnongren.work.ui.home.model.SpecificationBean;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 自定义dialog
 * Created by xuyougen on 2018/3/5.
 * <p>
 * 使用方法
 * new CustomDialog.Builder({@link Context})
 * .setTitle("标题")
 * .setContent("提示内容")
 * .setListener({@link OnButtonClickListener))
 * .build()
 * .show();
 */

public class AddToCartDialog extends Dialog {
    public AddToCartDialog(@NonNull Context context) {
        super(context);
    }

    public AddToCartDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置dialog 窗体的宽度
        if (getWindow() != null) {
            getWindow().getAttributes().width = WindowManager.LayoutParams.MATCH_PARENT;
            getWindow().getAttributes().gravity = Gravity.BOTTOM;
        }
    }

    public static class Builder implements AddToCarView {
        private Context mContext;
        private String mId;
        private OnButtonClickListener mListener;
        private AddToCarPresenter mPresenter;
        private List<SpecificationBean> mList;
        private AddToCartAdapter mAdapter;

        public Builder(Context context) {
            mContext = context;
        }

        public Builder setGoodsId(String id) {
            mId = id;
            return this;
        }

        public Builder setListener(OnButtonClickListener listener) {
            mListener = listener;
            return this;
        }

        public AddToCartDialog build() {
            mList = new ArrayList<>();
            mPresenter = new AddToCarPresenter();
            mPresenter.attach(this);
            final AddToCartDialog dialog = new AddToCartDialog(mContext, R.style.CustomDialog);
            View layout = View.inflate(mContext, R.layout.layout_add_to_cart_dialog, null);
            TextView confirm = layout.findViewById(R.id.tv_confirm_custom_dialog);
            RecyclerView recyclerView = layout.findViewById(R.id.rv_list);
            mAdapter = new AddToCartAdapter();
            recyclerView.setAdapter(mAdapter);
            recyclerView.setLayoutManager(new LinearLayoutManager(mContext));

            confirm.setOnClickListener(v -> {
                dialog.dismiss();
                if (mListener != null) {
                    mListener.onConfirm(dialog);
                }
            });

            //将布局添加到 dialog 中
            dialog.setContentView(layout);
            getSpecificationData();
            return dialog;
        }

        private void getSpecificationData() {
            mPresenter.getGoodsSpecList(mId);
        }

        @Override
        public void showLoadingView() {
        }

        @Override
        public void hideLoadingView() {

        }

        @Override
        public void onNetworkError() {

        }

        public void onChangedSpecNum() {
            getSpecificationData();
            Global.notifyCartNumChanged(mContext);
        }

        @Override
        public void onGetGoodsSpecList(List<SpecificationBean> list) {
            if (list.isEmpty())
                ToastHelper.getInstance(mContext).showNormal("此商品暂无规格");
            mList.clear();
            mList.addAll(list);
            mAdapter.notifyDataSetChanged();
        }


        public class AddToCartAdapter extends RecyclerView.Adapter<AddToCartAdapter.Holder> {

            @NonNull
            @Override
            public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                Holder holder = new Holder(LayoutInflater.from(mContext).inflate(R.layout.item_add_to_cart, parent, false));
                holder.plus.setOnClickListener(v -> changeSpecNum(holder, mList.get(holder.getAdapterPosition()), true));
                holder.reduce.setOnClickListener(v -> changeSpecNum(holder, mList.get(holder.getAdapterPosition()), false));
                return holder;
            }

            @Override
            public void onBindViewHolder(@NonNull Holder holder, int position) {
                SpecificationBean bean = mList.get(position);
                holder.item_price.setText(String.format("￥%s", bean.getPrice()));
                holder.item_sku_name.setText(TextUtils.isEmpty(bean.getSkuName()) ? "" :String.format("/%s", bean.getSkuName()));
                holder.item_unit_price.setText(String.format("单价：￥%s", bean.getUnitPrice()));
                holder.tv_num.setText(String.valueOf(bean.getShopCarNum()));
            }

            private void changeSpecNum(@NonNull Holder holder, SpecificationBean bean, boolean isPlus) {
                String numStr = holder.tv_num.getText().toString();
                if (numStr.trim().length() == 0) return;
                int num = Integer.parseInt(numStr);
                if (isPlus)
                    mPresenter.changeSpecNum(bean.getSkuId(), ++num);
                else
                    mPresenter.changeSpecNum(bean.getSkuId(), num <= 0 ? 0 : --num);
            }

            @Override
            public int getItemCount() {
                return mList.size();
            }

            public class Holder extends RecyclerView.ViewHolder {
                @BindView(R.id.item_price)
                TextView item_price;
                @BindView(R.id.item_sku_name)
                TextView item_sku_name;
                @BindView(R.id.item_unit_price)
                TextView item_unit_price;
                @BindView(R.id.iv_plus)
                ImageView plus;
                @BindView(R.id.iv_reduce)
                ImageView reduce;
                @BindView(R.id.tv_num)
                TextView tv_num;

                public Holder(View itemView) {
                    super(itemView);
                    ButterKnife.bind(this, itemView);
                }
            }
        }
    }

    /**
     * 监听接口
     */
    public interface OnButtonClickListener {
        void onConfirm(Dialog dialog);
    }

}
